package com.allwe.client.simple;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * kafka生产者配置
 *
 * @Author: AllWe
 * @Date: 2024/09/24/17:57
 */
@Slf4j
public class HelloKafkaProducer {
    public static void main(String[] args) {
        // 设置属性
        Properties properties = new Properties();
        // 指定连接的kafka服务器地址，多台就用“,”隔开，如果某一台宕机生产者依然可以连接
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "39.107.66.31:9092");
        // 设置key和value的序列化器，使java对象转换成二进制数组
        properties.put("key.serializer", StringSerializer.class);
        properties.put("value.serializer", StringSerializer.class);

        // new一个生产者producer
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        try {
            ProducerRecord<String, String> producerRecord;
            try {
                // 构建消息
                producerRecord = new ProducerRecord<>("topic_1", "student", "allwe");
                // 发送消息
                producer.send(producerRecord);
                System.out.println("消息发送成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            // 释放连接
            producer.close();
        }
    }
}
